<template>
  <div>
    <el-button :loading="printLoading" type="primary" size="small" class="print-btn flex-center" @click="printTable()">
      <div class="flex-center">打印 <img :src="printIcon" alt=""></div>
    </el-button>
    <div v-if="printConfig" id="printArea" class="printArea">
      <div class="print-content">
        <div class="title">{{ printConfig.title }}</div>
        <div class="table">
          <div v-if="printData && printData.processStatus === PROGRESS_STEP.FINISHED" class="status-icon">
            <img :src="success" alt="success">
          </div>
          <div v-else-if="printData && printData.processStatus === 3" class="status-icon">
            <img :src="revokeImg" alt="revoke">
          </div>
          <template v-for="(config, index) in printConfig.config">
            <template v-if="config">
              <div v-if="(!config.condition || handelCondition(config.condition, printData)) && hasData(printData, config)" :key="index" >
                <div v-if="config.subTitle" class="subTitle dy-fontSize bb">{{ config.subTitle }}</div>
                <!-- 表单格式 -->
                <template v-if="config.type === 'form'">
                  <template v-for="(child, jindex) in config.children" >
                    <el-row v-if="!child.condition || handelCondition(child.condition, printData)" :key="jindex" type="flex" class="cell bb form-type">
                      <template v-for="(dataItem, kindex) in child.list">
                        <el-col :key="'label'+kindex" :span="config.labelSpan || 4" class="response-item br dy-fontSize">{{ dataItem.label }}</el-col>
                        <el-col v-if="['richEditor', 'titleExplain'].includes(dataItem.type)" :key="'value'+kindex" :span="(12) - (config.labelSpan || 4)" :class="{'br': kindex !==1}" class="response-item dy-fontSize" style="flex-flow: column wrap;align-items: flex-start;" v-html="getPrintData(printData, dataItem)" />
                        <el-col v-else :key="'value'+kindex" :span="(12) - (config.labelSpan || 4)" :class="{'br': kindex !==1}" class="response-item dy-fontSize">{{ getPrintData(printData, dataItem) }}<span v-if="dataItem.subLabel">（{{ dataItem.subLabel }}：{{ getPrintData(printData, dataItem,'subKeyword') }}）</span></el-col>
                      </template>
                    </el-row>
                  </template>
                </template>
                <Table v-else-if="config.type === 'table' || config.type === 'tableSingle' " :printData="printData" :config="config" />
                <Process v-else-if="processData && config.type === 'process'" :process-data="processData" />
              </div>
            </template>
          </template>
        </div>
        <div class="footre">
          <span class="tooltip" style="margin-right:40px;">打印时间：{{ nowTime | format('YYYY/MM/DD HH:mm') }}</span>
          <span class="tooltip">打印人：{{ userInfo.userName }}</span>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import { getContentStyle } from './printTemplateCSS';
import configData from './configData'; // 配置数据
import { PROGRESS_STEP } from '@/utils/const/energy';
// tool
import { format } from '@/filters/date';
import { mapState } from 'vuex';
import { moneyFilter } from '@/filters/number';
// mixins
import extendData from './mixins/extendData';
// comp
import Table from './table';
import Process from './processData';
// api
import { getPrintProcess } from '@/api/setting';
// png
import success from '@/assets/auditProcess/process_status_4.png';
import close from '@/assets/auditProcess/process_status_6.png';
import printIcon from '@/assets/supplier/printIcon.png';
import revokeImg from '@/assets/auditProcess/process_status_3.png';
import { PROCESS_TYPE } from '@/utils/const/process';

export default {
  filters: { moneyFilter, format },
  components: { Table, Process },
  mixins: [extendData],
  props: {
    printData: {
      type: Object | Array,
      default: null
    },
    processType: {
      type: Number,
      default: -1
    },
    processId: {
      type: Number | String,
      default: ''
    },
    approvalModulePrintConfig: { // 自定义审批的打印配置
      type: Object,
      default: null
    }
  },
  data() {
    return {
      PROGRESS_STEP,
      printIcon, success, close, revokeImg,
      printLoading: false,
      processData: null,
      nowTime: new Date()
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    printConfig() {
      if (this.processType === -1) return null;
      if (this.processType === PROCESS_TYPE.APPROVAL) return this.approvalModulePrintConfig;
      return configData[this.processType] || null;
    }
  },
  methods: {
    preview() {
      // 判断iframe是否存在，不存在则创建iframe
      var iframe = document.getElementById('print-iframe');
      if (iframe) {
        document.body.removeChild(iframe);
      }
      const printAreaContent = document.getElementById('printArea').innerHTML;
      iframe = document.createElement('IFRAME');
      let doc = null;
      iframe.setAttribute('id', 'print-iframe');
      iframe.setAttribute('style', 'position:absolute;width:0px;height:0px;left:-500px;top:-500px;opacity: 0;');
      // iframe.setAttribute('style', 'z-index: 3000;position:fixed;width:1000px;height:100%;left:50%;top:0px;opacity: 1;margin-left: -500px;');
      document.body.appendChild(iframe);
      doc = iframe.contentWindow.document;
      // 这里可以自定义样式
      doc.write(getContentStyle('12px', '3px'));
      doc.write('<div>' + printAreaContent + '</div>');
      doc.close();
      iframe.contentWindow.focus();
      iframe.contentWindow.print();
      // document.getElementById('printArea').style.display = 'none';
      this.printLoading = false;
    },
    printTable() {
      if (!this.printData) {
        this.$message.error('需要打印的数据错误');
        return;
      }
      this.nowTime = new Date();
      this.printLoading = true;
      if (this.processId) {
        getPrintProcess({ workFlowId: this.processId }).then(res => {
          if (res.data) this.processData = res.data;
          this.$nextTick(() => {
            this.preview();
          });
        }).catch(() => {
          this.$nextTick(() => {
            this.preview();
          });
        });
      } else {
      // document.getElementById('printArea').style.display = 'block';
        this.$nextTick(() => {
          this.preview();
        });
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.printArea {
  position: fixed;
  display: none;
  z-index: -2000;
  width: 1000px;
  background: rgba($color: #000000, $alpha: 0.5);
  left: 50%;
  top: 0;
  margin-left: -500px;
  padding: 20px;
}
.print-btn {
  width: 80px;
  padding: 0;
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  padding: 7px 16px;
  img {
    width: 16px;
    margin-left: 3px;
  }
}
.flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}
.test-dialog {
  position: fixed;
  z-index: 2000;
  width: 1000px;
  background: #fff;
  left: 50%;
  top: 0;
  margin-left: -500px;
  padding: 20px;
}
</style>

